Can we match Any to a generic type? [Scala 2.8]
Posted
by
Jus12
on Stack Overflow
See other posts from Stack Overflow
or by Jus12
Published on 2011-02-01T06:08:47Z
Indexed on
2011/02/01
7:26 UTC
Read the original article
Hit count: 117
Please point me to correct link if this has been answered before.
I have this code:
def getResult(a:Any):Any = a
def getAnswer[T](i:Int) = {
val result = getResult(i)
result match {
case t:T => Some(t)
case _ => None
}
}
This gives me a unchecked warning
and everything matches to T
. For instance, when I do getAnswer[Int](2)
, I get Some(2)
(as expected). However, if I do getAnswer[String](2)
, I also get Some(2)
which is not expected (I need None
).
Is there any way to work around type erasure and somehow get getAnswer
to work correctly (i.e., return Some(result)
if and only if the result is of type T
)?
Thanks in advance.
© Stack Overflow or respective owner